package com.suyl.candy.weather.modules.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.suyl.candy.weather.modules.business.dao.CityDao;
import com.suyl.candy.weather.modules.business.entity.CityDO;
import com.suyl.candy.weather.modules.business.service.WeatherService;
import com.suyl.candy.weather.utils.DateUtils;
import com.suyl.candy.weather.utils.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Log4j2
@RestController
@RequestMapping("search")
public class WeatherController {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    WeatherService weatherService;

    @Autowired
    CityDao cityDao;

    @CrossOrigin
    @ResponseBody
    @GetMapping(value = "/city")
    public Object getWeather(HttpServletRequest req, HttpServletResponse resp, @RequestParam("city") String cityName, String date) {
        try {
            Object city = redisUtil.getBoundHashOps("citys", cityName);
            if (StringUtils.isEmpty(city)) {
                synchronized (this) {
                    city = redisUtil.getBoundHashOps("citys", cityName);
                    if (StringUtils.isEmpty(city)) {
                        CityDO cityDO = cityDao.findByCityEn(cityName);
                        if (cityDO == null) {
                            // 不存在城市
                            return "不存在城市";
                        }
                        city = JSONObject.toJSONString(cityDO);
                        redisUtil.putBoundHashOps("citys", cityName, city);
                    }
                }
            }
            String cityCode = JSONObject.parseObject(city.toString(), CityDO.class).getId().toString();
            return weatherService.searchWeather(cityCode, StringUtils.isEmpty(date) ? DateUtils.getDate() : date);
        } catch (Exception e) {
            log.error("【天气查询】发生异常，请联系管理员！！！");
        }
        return null;
    }
}
